package cloud.tianai.mate.captcha.interceptor.impl;

import cloud.tianai.captcha.common.AnyMap;
import cloud.tianai.captcha.common.response.ApiResponse;
import cloud.tianai.captcha.common.response.CodeDefinition;
import cloud.tianai.captcha.generator.common.model.dto.GenerateParam;
import cloud.tianai.captcha.interceptor.Context;
import cloud.tianai.captcha.validator.common.model.dto.ImageCaptchaTrack;
import cloud.tianai.captcha.interceptor.CaptchaInterceptor;
import cloud.tianai.captcha.application.vo.CaptchaResponse;
import cloud.tianai.captcha.application.vo.ImageCaptchaVO;
import cloud.tianai.mate.captcha.interceptor.group.FeaturesCaptchaInterceptorGroup;

import java.util.Collections;

public class DisableCaptchaInterceptor implements CaptchaInterceptor {
    public static final CodeDefinition DISABLED_DEFINITION = new CodeDefinition(60002, "disabled");


    public static final String DISABLE_KEY = "disable";

    @Override
    public String getName() {
        return "disable_check";
    }

    @Override
    public ApiResponse<?> beforeValid(Context context, String type, ImageCaptchaTrack imageCaptchaTrack, AnyMap validData) {
        AnyMap featureMap = context.getData(FeaturesCaptchaInterceptorGroup.DATA_FEATURES, AnyMap.class);
        if (featureMap != null && featureMap.containsKey(DISABLE_KEY)) {
            context.allEnd();
            return ApiResponse.ofMessage(DISABLED_DEFINITION);
        }
        return ApiResponse.ofSuccess();
    }

    @Override
    public CaptchaResponse<ImageCaptchaVO> beforeGenerateCaptcha(Context context, String type, GenerateParam param) {
        AnyMap featureMap = context.getData(FeaturesCaptchaInterceptorGroup.DATA_FEATURES, AnyMap.class);

        if (featureMap == null || !featureMap.containsKey(DISABLE_KEY)) {
            return null;
        }
        ImageCaptchaVO imageCaptchaVO = new ImageCaptchaVO();
        imageCaptchaVO.setType("DISABLED");
        imageCaptchaVO.setData(Collections.singletonMap("value", "请求次数过多，请稍后再试"));
        context.allEnd();
        return CaptchaResponse.of("-1", imageCaptchaVO);
    }
}
